<?php
/**
 * @Author: xuzhiyi
 * @Date:   2016-02-09 20:41:46
 * @Last Modified by:   xuzhiyi
 * @Last Modified time: 2016-02-12 17:31:52
 * ------------------------------------------------ *
 * 角色管理 *
 * ------------------------------------------------ */ 

namespace Admin\Model;

class RolesModel extends CommonModel {

	public function getRoles(){
		$role=M('roles')->where('roleFlag!=-1')->select();
		if(!$role){
			return false;
		}
		$roles=array();
		foreach($role as $key=>$val){
			$roles[$key]=$val;
			$a=M('auths')->order('concat(authPath,authId)')
			->Field('authName,authIco,authId,parentId,concat(authPath,authId) as bPath')
			->where('authId in('.$val["grant"].') and authFlag!=-1')
			->select();
			;
			$roles[$key]['grantName']=$a;
		}
		return $roles;
	}


	public function addRoles(){
		$roleName=I('roleName');
		//权限格式化
		$auth=I('auth');
		$auth=implode($auth,',');
		$auth=array_unique(explode(',',$auth));
		$auth=implode($auth,',');

		$data = array();
		$data["roleName"] = I("roleName");
		$data["grant"] = $auth;
		$data["createTime"] = date('Y-m-d H:i:s');
		$data["roleFlag"] = 1;
	    if($this->checkEmpty($data)){
			$r = M('roles');
			$rs = $r->add($data);
			if(false !== $rs){
				return true;
			}
		}
		return false;
	}


	public function editRoles(){
	 	$roleId = (int)I("roleId",0);
	 	
		//权限格式化
		$auth=I('auth');
		$auth=implode($auth,',');
		$auth=array_unique(explode(',',$auth));
		$auth=implode($auth,',');

		$data = array();
		$data["grant"] = $auth;
		
	    if($this->checkEmpty($data)){
			$rs = M('roles')->where("roleId=".$roleId)->save($data);
			if(false !== $rs){
				
				//实时更新当前用户权限
				if(session('admin.managerRoleId')==$roleId){
					$grant = explode(',',$auth);
					session('admin.grant',$grant);
				}
				return true;
			}
		}
		return false;
	 } 

	 public function delRoles(){
	 	$roleId = (int)I('roleId');
	 	$r = M('roles');
	 	$r->roleFlag=-1;
	    $rs = $r->where("roleId=".$roleId)->save();
		if(false !== $rs){
			return true;
		}
		return false;
	 }

}